package com.best.intelligentTrolley.serial_port

import java.io.InputStream

/**
 * author: shihao
 * date: 2021/3/3 17:03
 * description:
 */
abstract class SerialPortReadThread(private var inputStream: InputStream) : Thread() {
    private var byteArray: ByteArray = ByteArray(1024)

    //    private var tempArray: ByteArray = byteArrayOf()
    private var tempString: String = ""

    /**
     * 收到数据
     */
//    abstract fun onDataReceived(bytes: ByteArray)
    abstract fun onDataReceived(text: String)
    abstract fun onRawDataReceived(text: String)

    override fun run() {
        super.run()
        while (!isBreak) {
            if (inputStream.available() <= 0) {
                sleep(10)
                continue
            }
            try {
                val size: Int = inputStream.read(byteArray)
                if (size <= 0) {
                    return
                }
                val readBytes = ByteArray(size)
                System.arraycopy(byteArray, 0, readBytes, 0, size)
                val data = KTDataUtils.byteArrayToHex(readBytes)
                onRawDataReceived(data)
                tempString += data
                val regex = Regex("7E\\s7E.+?E7\\sE7")
                val regex1 = Regex("9E\\s9E.+?E9\\sE9")
                if (regex.containsMatchIn(tempString)) {
                    var result = regex.find(tempString)
                    while (result != null) {
                        val text = result.value
                        onDataReceived(text)
                        tempString = regex.split(tempString, 2)[1]
                        result = regex.find(tempString)
                    }
                }else if (regex1.containsMatchIn(tempString)) {
                    var result = regex1.find(tempString)
                    while (result != null) {
                        val text = result.value
                        onDataReceived(text)
                        tempString = regex1.split(tempString, 2)[1]
                        result = regex1.find(tempString)
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                return
            }
        }
    }

    @Synchronized
    override fun start() {
        super.start()
    }

    private var isBreak = false

    /**
     * 关闭线程 释放资源
     */
    open fun release() {
        isBreak = true
    }
}